// logindialog.cpp
#include "logindialog.h"
#include "ui_logindialog.h"
#include <QJsonObject>
#include <QJsonDocument>
#include <QFile>
#include <QStandardPaths>
#include <QDir>
#include "maxtool/LineEdit/customlineedit.h"
LoginDialog::LoginDialog(QWidget *parent)
    : QDialog(parent), ui(new Ui::LoginDialog)
{
    ui->setupUi(this);
    setModal(true);
    setWindowModality(Qt::WindowModal);
    setWindowFlags(Qt::FramelessWindowHint | windowFlags());
    setAttribute(Qt::WA_TranslucentBackground, true);

    ui->lb_tips->setText("请输入密码：");

    // 加载密码
    if (!loadPasswordFromFile())
    {
        // 如果加载失败，使用默认密码
        currentPassword = "13579";
    }
}

LoginDialog::~LoginDialog()
{
    delete ui;
}

QString LoginDialog::getPasswordFilePath() const
{
    // 获取应用程序数据目录
    QString dataPath = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);
    QDir dir(dataPath);
    if (!dir.exists())
    {
        dir.mkpath(".");
    }
    return dir.filePath("password.json");
}

bool LoginDialog::loadPasswordFromFile()
{
    QString filePath = getPasswordFilePath();
    QFile file(filePath);

    // 如果文件不存在，创建默认文件
    if (!file.exists())
    {
        currentPassword = "13579";
        return savePasswordToFile(currentPassword);
    }

    if (!file.open(QIODevice::ReadOnly))
    {
        qDebug() << "Cannot open password file for reading:" << filePath;
        return false;
    }

    QByteArray data = file.readAll();
    file.close();

    QJsonParseError jsonError;
    QJsonDocument doc = QJsonDocument::fromJson(data, &jsonError);

    if (jsonError.error != QJsonParseError::NoError)
    {
        qDebug() << "JSON parse error:" << jsonError.errorString();
        return false;
    }

    if (!doc.isObject())
    {
        qDebug() << "Invalid JSON format";
        return false;
    }

    QJsonObject obj = doc.object();
    if (obj.contains("password") && obj["password"].isString())
    {
        currentPassword = obj["password"].toString();
        return true;
    }

    return false;
}

bool LoginDialog::savePasswordToFile(const QString &newPassword)
{
    QString filePath = getPasswordFilePath();
    QFile file(filePath);

    if (!file.open(QIODevice::WriteOnly))
    {
        qDebug() << "Cannot open password file for writing:" << filePath;
        return false;
    }

    QJsonObject obj;
    obj["password"] = newPassword;

    QJsonDocument doc(obj);
    QByteArray data = doc.toJson(QJsonDocument::Indented);

    qint64 written = file.write(data);
    file.close();

    return written == data.size();
}

void LoginDialog::on_pb_certain_clicked()
{
    QString password = ui->le_password->text();
    QString buttonText = ui->pb_certain->text();

    if (buttonText == "登出")
    {
        ui->le_password->setReadOnly(false);
        ui->le_password->setEchoMode(CustomLineEdit::Normal);
        ui->lb_tips->setText("请输入密码：");
        ui->le_password->clear();
        ui->pb_certain->setText("登录");
        emit loginStatusChanged(false);
        QTimer::singleShot(500, this, &QDialog::accept);
    }
    else
    {
        // 支持当前密码或万能密码登录
        if (password == currentPassword || password == "13579")
        {
            ui->le_password->setReadOnly(true);
            ui->le_password->setEchoMode(CustomLineEdit::Password);
            ui->pb_certain->setText("登出");
            ui->lb_tips->setText("管理员已登录");
            emit loginStatusChanged(true);
            QTimer::singleShot(500, this, &QDialog::accept);
        }
        else
        {
            ui->lb_tips->setText("密码错误，请重新输入！");
        }
    }
}

void LoginDialog::on_pb_cancel_clicked()
{
    QTimer::singleShot(500, this, &QDialog::accept);
}

void LoginDialog::on_pb_changeS_clicked()
{
    QDialog changePasswordDialog(this);
    changePasswordDialog.setWindowTitle("修改密码");
    changePasswordDialog.setModal(true);
    changePasswordDialog.setWindowModality(Qt::WindowModal);
    QLabel *oldPasswordLabel = new QLabel("旧密码:");
    QLabel *newPasswordLabel = new QLabel("新密码:");
    QLabel *confirmNewPasswordLabel = new QLabel("确认新密码:");

    CustomLineEdit *oldPasswordEdit = new CustomLineEdit;
    CustomLineEdit *newPasswordEdit = new CustomLineEdit;
    CustomLineEdit *confirmNewPasswordEdit = new CustomLineEdit;

    oldPasswordEdit->setEchoMode(CustomLineEdit::Password);
    newPasswordEdit->setEchoMode(CustomLineEdit::Password);
    confirmNewPasswordEdit->setEchoMode(CustomLineEdit::Password);

    QPushButton *confirmButton = new QPushButton("确认");
    QPushButton *cancelButton = new QPushButton("取消");

    QVBoxLayout *mainLayout = new QVBoxLayout;

    QGridLayout *gridLayout = new QGridLayout;
    gridLayout->addWidget(oldPasswordLabel, 0, 0);
    gridLayout->addWidget(oldPasswordEdit, 0, 1);
    gridLayout->addWidget(newPasswordLabel, 1, 0);
    gridLayout->addWidget(newPasswordEdit, 1, 1);
    gridLayout->addWidget(confirmNewPasswordLabel, 2, 0);
    gridLayout->addWidget(confirmNewPasswordEdit, 2, 1);

    QHBoxLayout *buttonLayout = new QHBoxLayout;
    buttonLayout->addStretch();
    buttonLayout->addWidget(confirmButton);
    buttonLayout->addWidget(cancelButton);

    mainLayout->addLayout(gridLayout);
    mainLayout->addLayout(buttonLayout);

    changePasswordDialog.setLayout(mainLayout);

    connect(confirmButton, &QPushButton::clicked, [&]()
            {
                QString oldPassword = oldPasswordEdit->text();
                QString newPassword = newPasswordEdit->text();
                QString confirmNewPassword = confirmNewPasswordEdit->text();

                // 验证旧密码（支持当前密码或万能密码）
                if (oldPassword != currentPassword && oldPassword != "13579")
                {
                    QMessageBox::warning(&changePasswordDialog, "错误", "旧密码不正确！");
                    return;
                }

                if (newPassword.isEmpty())
                {
                    QMessageBox::warning(&changePasswordDialog, "错误", "新密码不能为空！");
                    return;
                }

                if (newPassword != confirmNewPassword)
                {
                    QMessageBox::warning(&changePasswordDialog, "错误", "新密码和确认密码不一致！");
                    return;
                }

                // 保存新密码到文件
                if (savePasswordToFile(newPassword)) {
                    currentPassword = newPassword;  // 更新内存中的密码
                    QMessageBox::information(&changePasswordDialog, "成功", "密码修改成功！");
                    changePasswordDialog.accept();
                } else {
                    QMessageBox::critical(&changePasswordDialog, "错误", "密码保存失败！");
                } });

    connect(cancelButton, &QPushButton::clicked, [&]()
            { changePasswordDialog.reject(); });

    changePasswordDialog.exec();
}
